package com.jay.syncdrawing.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

import com.jay.syncdrawing.AppManager;
import com.jay.syncdrawing.R;
import com.jay.syncdrawing.utils.BitmapUtil;
import com.jay.syncdrawing.utils.Constant;
import com.jay.syncdrawing.utils.DateUtils;
import com.jay.syncdrawing.utils.DrawType;
import com.jay.syncdrawing.utils.FileUtils;
import com.jay.syncdrawing.utils.ToastUtils;
import com.jay.syncdrawing.widget.ColorPickerDialog;
import com.jay.syncdrawing.widget.DrawView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private DrawView drawView;
	private ColorPickerDialog colorDialog;
	private PopupWindow pop;
	public static int color = Color.BLUE;
	private TextView tv_width;
	private SeekBar sb;
	private Button btn_width;
	private UpLoadThread UpLoadThread;
	private String ip = "";
	private int port;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int num = msg.getData().getInt("width");
			tv_width.setText(""+ num + "px");
			drawView.setBlock(num);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppManager.getAppManager().addActivity(this);
		setContentView(R.layout.activity_main);

		findView();
		setEvent();
	}

	private void findView() {
		drawView = (DrawView) findViewById(R.id.drawview);
		btn_width = (Button) findViewById(R.id.btn_width);
	}

	private void setEvent() {
		ip = getIntent().getStringExtra("ip");
		port = getIntent().getIntExtra("port", 0);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_circle:
			drawView.drawType = DrawType.circle;
			break;
		case R.id.btn_brush:
			drawView.drawType = DrawType.brush;
			break;
		case R.id.btn_line:
			drawView.drawType = DrawType.line;
			break;
		case R.id.btn_rectangle:
			drawView.drawType = DrawType.rectangle;
			break;
		case R.id.btn_triangle:
			drawView.drawType = DrawType.triangle;
			break;
		case R.id.btn_revoke:
			drawView.revoke();
			break;
		case R.id.btn_eraser:
			drawView.drawType = DrawType.eraser;
			break;
		case R.id.btn_color:
			colorDialog = new ColorPickerDialog(MainActivity.this,
					R.style.dialog, color,
					new ColorPickerDialog.OnColorChangedListener() {
				@Override
				public void colorChanged(int color) {
					drawView.setColor(color);
				}
			});
			colorDialog.setCanceledOnTouchOutside(true);// 设置点击Dialog外部任意区域关闭Dialo
			colorDialog.show();
			break;
		case R.id.btn_width:
			showPop();
			break;
		case R.id.btn_clear:
			drawView.clearAll();
			break;
		case R.id.btn_save:
			saveBitmap();
			break;
		}
	}

	private void saveBitmap(){
		drawView.setEnabled(false);
		Bitmap bmBitmap = drawView.getCanvasSnapshot();
		String pathName = FileUtils.createDir(Constant.PATHNAME)+"/";
		String picName = DateUtils.getDate()+".png";
		BitmapUtil.saveBitmapToSdCard(bmBitmap, pathName+picName);
		drawView.cleanDrawingCache();
		System.out.println(pathName+picName);
		//这里应该检验一下图片是否存在
		ToastUtils.showToast("保存成功！");
	}

	private void showPop(){
		// 利用layoutInflater获得View
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.pop_width_seekbar, null);
		// 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
		PopupWindow window = new PopupWindow(view,
				300,
				150);

		// 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
		window.setFocusable(true);
		window.setOutsideTouchable(true);
		window.setBackgroundDrawable(new BitmapDrawable());
		sb = (SeekBar) view.findViewById(R.id.progresss);
		tv_width = (TextView) view.findViewById(R.id.tv_width);
		sb.setOnSeekBarChangeListener(seekbarChangeListener);

		// 设置popWindow的显示和消失动画
		window.setAnimationStyle(R.style.popwindow_anim_style);
		window.showAsDropDown(btn_width);
	}

	private OnSeekBarChangeListener seekbarChangeListener = new OnSeekBarChangeListener() {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			// TODO Auto-generated method stub
			Message message = new Message();
			Bundle bundle = new Bundle();// 存放数据
			int num = seekBar.getProgress();
			bundle.putInt("width", num);
			message.setData(bundle);
			message.what = 0;
			handler.sendMessage(message);
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}
	};

	class UpLoadThread extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			while (true) {
				try {
					//循环发送图片
					uploadBySocket(ip, port);
					Thread.sleep(500);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	//通过socket发送图片
	private boolean uploadBySocket(String host, int port) throws Exception {
		drawView.setEnabled(false);
		Bitmap bmBitmap = drawView.getCanvasSnapshot();
		String BOUNDARY = java.util.UUID.randomUUID().toString();  
		// 由于HttpURLConnection中会缓存数据, 上传较大文件时会导致内存溢出, 所以我们使用Socket传输
		Socket socket = new Socket(host, port);
		OutputStream out = socket.getOutputStream();
		PrintStream ps = new PrintStream(out, true, "UTF-8");
		// 写出请求头
		ps.println("POST /14_Web/servlet/LoginServlet HTTP/1.1");
		ps.println("Content-Type: multipart/form-data; boundary=" + BOUNDARY);
		//将图片BitMap转化成直接输入流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		InputStream in = new ByteArrayInputStream(baos.toByteArray());
		// 写出数据
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) != -1)
			out.write(buf, 0, len);
		in.close();
		out.close();
		return true;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//启动同步线程
		UpLoadThread = new UpLoadThread();
		UpLoadThread.start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			//调用双击退出函数
			AppManager.getAppManager().exitBy2Click();
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

}
